package com.mcxx.modules.miniSalvation.order.service.write;

import com.mcxx.common.exception.BizException;
import com.mcxx.modules.miniSalvation.check.dao.read.CheckReadDao;
import com.mcxx.modules.miniSalvation.family.dto.FamilyMemberDTO;
import com.mcxx.modules.miniSalvation.order.dao.read.OrderReadDao;
import com.mcxx.modules.miniSalvation.order.dao.write.OrderWriteDao;
import com.mcxx.modules.miniSalvation.order.dto.OrderDTO;
import com.mcxx.modules.miniSalvation.order.dto.OrderStateVerifyDTO;
import com.mcxx.modules.miniSalvation.order.entity.OrderEntity;
import com.mcxx.modules.miniSalvation.order.entity.OrderStateEntity;
import com.mcxx.util.Constant;
import com.mcxx.util.DateUtil;
import com.mcxx.util.FailureCode;
import com.yinhai.ta404.core.security.vo.UserAccountVo;
import com.yinhai.ta404.core.transaction.annotation.TaTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Slf4j
@Service
@TaTransactional
public class OrderWriteService {
    @Resource
    private OrderWriteDao orderWriteDao;
    @Autowired
    private OrderReadDao orderReadDao;
    @Autowired
    private CheckReadDao checkReadDao;



    public void insertIgnoreNull(OrderEntity orderEntity) {
        int rows = orderWriteDao.insertIgnoreNull(orderEntity);
        if (rows < 1) {
            throw new BizException(FailureCode.ERR_9999);
        }
    }


    public void inserts(List<OrderEntity> orderEntityList) {
        int rows = orderWriteDao.inserts(orderEntityList);
        if (rows < 1) {
            throw new BizException(FailureCode.ERR_9999);
        }
    }


    public int updateIgnoreNull(OrderEntity orderEntity) {
        int rows = orderWriteDao.updateIgnoreNull(orderEntity);
        if (rows < 1) {
            throw new BizException(FailureCode.ERR_60000);
        }
        return rows;
    }


    public int updateForCountryRevoke(OrderEntity orderEntity) {
        int rows = orderWriteDao.updateForCountryRevoke(orderEntity);
        if (rows < 1) {
            throw new BizException(FailureCode.ERR_60000);
        }
        return rows;
    }




    public void updateByIdAndVersion(OrderEntity orderEntity) {
        int rows = orderWriteDao.updateByIdAndVersion(orderEntity);
        if (rows < 1) {
            throw new BizException(FailureCode.ERR_60000);
        }
    }

    public int deleteById(String orderId) {
        return orderWriteDao.deleteByOrderId(orderId);
    }


    public void updateOrderRecheckFlag(String orderId, int recheckFlag, String version) {
        orderWriteDao.updateOrderRecheckFlag(orderId, recheckFlag, version);
    }


    public int updateState(OrderStateEntity orderStateEntity){
        return orderWriteDao.updateState(orderStateEntity);
    }


    public int updateSalaryDate(String orderId, String startMonth, String endMonth){
        return orderWriteDao.updateSalaryDate(orderId, startMonth, endMonth);
    }


    public void batchChangeExpireDate(Map<String, Object> map) {
        int rows = orderWriteDao.batchChangeExpireDate(map);
        if (rows < 1) {
            throw new BizException(FailureCode.ERR_9999);
        }
    }


    public void batchChangeRecheckFlag(Map<String, Object> map) {
        int rows = orderWriteDao.batchChangeRecheckFlag(map);
        if (rows < 1) {
            throw new BizException(FailureCode.ERR_9999.getCode(),FailureCode.ERR_9999.getMsg());
        }
    }


    public void batchDeleteRecheckOrder(List<String> orderIdList) {
        int rows = orderWriteDao.batchDeleteRecheckOrder(orderIdList);
        if (rows < 1) {
            throw new BizException(FailureCode.ERR_9999.getCode(),FailureCode.ERR_9999.getMsg());
        }
    }


    public void updateOrderNextActviti(OrderDTO orderDTO, String nextActviti, String preBizState){
        if(Constant.BizStateNew.APPROVE_REJECT.equals(orderDTO.getState()) &&
                Constant.BizStateNew.AUDIT_REFUSE.equals(nextActviti) == false &&
                Constant.BizStateNew.APPROVE_ING.equals(nextActviti) == false){

            return;
        }
        if(orderDTO.getState().equals(nextActviti)){

            return;
        }
        OrderStateEntity orderStateEntity = new OrderStateEntity(orderDTO.getId(),
                nextActviti, preBizState,
                nextActviti,
                orderDTO.getVersion());
        int rst = this.updateState(orderStateEntity);
        if(rst <= 0){
            log.info("orderId = {},说明修改状态信息失败", orderDTO.getId());
            throw new BizException("-1", "订单状态异常，修改失败");
        }
    }


    public void updateOrderState(OrderDTO orderDTO, String curBizState, String nextBizState){
        if(Constant.BizStateNew.APPROVE_REJECT.equals(orderDTO.getState())
                || Integer.parseInt(curBizState) >= Integer.parseInt(nextBizState)){

            return;
        }
        OrderStateEntity orderStateEntity = new OrderStateEntity(orderDTO.getId(),
                nextBizState, orderDTO.getVersion());
        int rst = this.updateState(orderStateEntity);
        if(rst <= 0){
            log.info("orderId = {},说明修改状态信息失败", orderDTO.getId());
            throw new BizException("-1", "订单状态异常，修改失败");
        }
    }


    public void updateOrderState(List<OrderDTO> orderDTOList, String curBizState, String preBizState){
        for(OrderDTO orderDTO : orderDTOList){
            if(Constant.BizStateNew.APPROVE_REJECT.equals(orderDTO.getState())){

                continue;
            }
            OrderStateEntity orderStateEntity = new OrderStateEntity(orderDTO.getId(), curBizState, preBizState, orderDTO.getVersion());
            int cnt = this.updateState(orderStateEntity);
            if(cnt <= 0){
                throw new BizException("-1", "修改业务的状态异常");
            }
        }
    }


    public void updateOrderFamilyInfo(FamilyMemberDTO familyMemberDTO, UserAccountVo accountVo,  OrderDTO orderDTO){
        OrderEntity orderEntity = new OrderEntity();

        orderEntity.setOrderId(familyMemberDTO.getOrderId());

        orderEntity.setUpdateTime(new Date());

        orderEntity.setUpdateBy(accountVo.getUserId());

        orderEntity.setVersion(orderDTO.getVersion());

        orderEntity.setSaveMemberNumber(orderDTO.getSaveMemberNumber());

        updateByIdAndVersion(orderEntity);
    }


    public int revokeOrder(OrderStateVerifyDTO orderStateVerifyDTO){

        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderId(orderStateVerifyDTO.getOrderId());
        orderEntity.setState(orderStateVerifyDTO.getNextState());
        orderEntity.setBizState(orderStateVerifyDTO.getNextBizState());
        orderEntity.setVersion(orderStateVerifyDTO.getVersion());

        int rst = orderWriteDao.updateIgnoreNull(orderEntity);
        if(rst <= 0){
            throw new BizException(FailureCode.ERR_60001);
        }

        if(StringUtils.isNotBlank(orderStateVerifyDTO.getSourOrderId())){
            orderWriteDao.updateOrderRecheckFlag(orderStateVerifyDTO.getSourOrderId(),Constant.RECHECK_FLAG.NO, orderStateVerifyDTO.getVersion());
        }
        return rst;
    }


    public int backUpOrder(OrderStateVerifyDTO orderStateVerifyDTO){

        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderId(orderStateVerifyDTO.getOrderId());
        if(orderStateVerifyDTO.getState().equals(Constant.BizStateNew.APPROVE_REJECT)) {
            orderEntity.setState(orderStateVerifyDTO.getNextState());
            orderEntity.setBizState(Constant.BizStateNew.APPROVE_REJECT);
        } else {
            orderEntity.setState(orderStateVerifyDTO.getNextBizState());
            orderEntity.setBizState(orderStateVerifyDTO.getNextBizState());
        }
        orderEntity.setVersion(orderStateVerifyDTO.getVersion());

        int rst = orderWriteDao.updateIgnoreNull(orderEntity);
        if(rst <= 0){
            throw new BizException(FailureCode.ERR_60001);
        }
        return rst;
    }


    public void modifyOrder(OrderEntity orderEntity, String startMonth, String stopMonth, UserAccountVo userAccountVo,String cash) {
        OrderEntity updateEntity = new OrderEntity();
        updateEntity.setOrderId(orderEntity.getOrderId());
        switch (cash){
            case "1":

                if (StringUtils.isNotBlank(orderEntity.getStartMonth()) && StringUtils.isNotBlank(stopMonth)) {
                    if("2".equals(orderEntity.getDataFrom())){
                        updateEntity.setEndMonth(DateUtil.reduceMonth(stopMonth, 1));
                    }
                }
                updateEntity.setSuspendFlag(Constant.SuspendFlag.SUSPEND_STATE);
                //updateEntity.setType(Constant.OrderType.SUSPEND);
                updateEntity.setRecheckFlag(1);
                if("3".equals(orderEntity.getDataFrom())){
                    updateEntity.setSuspendFlag(Constant.SuspendFlag.NORMAL_STATE);
                    //updateEntity.setType(Constant.OrderType.SUSPEND);
                    updateEntity.setRecheckFlag(0);
                }

                updateEntity.setUpdateTime(DateUtil.getDate());
                updateEntity.setOperator(userAccountVo.getUsername());
                updateEntity.setOperDate(DateUtil.getDate());
                break;
            case "2":
                OrderEntity saveEntity = new OrderEntity();
                BeanUtils.copyProperties(orderEntity, saveEntity);
                saveEntity.setStartMonth(startMonth);
                saveEntity.setEndMonth(stopMonth);
                saveEntity.setBizState(Constant.BizState.APPROVE_YES);
                saveEntity.setRecheckFlag(0);
                saveEntity.setCreateTime(new Date());
                saveEntity.setUpdateTime(new Date());
                saveEntity.setType(Constant.OrderType.RECHECK);
                saveEntity.setSuspendFlag(Constant.SuspendFlag.NORMAL_STATE);
                this.insertIgnoreNull(saveEntity);
                break;
            case "4":

                updateEntity.setEndMonth(stopMonth);
                updateEntity.setRecheckFlag(0);
                //updateEntity.setType(Constant.OrderType.RECHECK);
                updateEntity.setUpdateTime(DateUtil.getDate());
                updateEntity.setSuspendFlag(Constant.SuspendFlag.NORMAL_STATE);
                break;
        }
        if(!"2".equals(cash)){
            this.updateIgnoreNull(updateEntity);
        }
    }


    public int deleteByOrderId(String id){
        return orderWriteDao.deleteByOrderId(id);
    }

    public int updateBizStateByQueryCheck(List<String> list){return orderWriteDao.updateBizStateByQueryCheck(list);}


    public int changeSaveMember(String type,String id){ return orderWriteDao.changeSaveMember(type,id); }

    public int changeSaveMemberNum(int saveMemberNumber,String id){ return orderWriteDao.changeSaveMemberNum(saveMemberNumber,id); }

    public Integer updateBackUpFile(String fileObjId,String orderId){return orderWriteDao.updateBackUpFile(fileObjId,orderId);}


    public void updateMemberInfo(FamilyMemberDTO familyMemberDTO,String relation){
        OrderEntity orderEntity = new OrderEntity();

         if(Constant.IsApply.YES.equals(familyMemberDTO.getIsApply())){
             orderEntity.setOrderId(familyMemberDTO.getOrderId());
             orderEntity.setApplyName(familyMemberDTO.getName());
             orderEntity.setApplyIdcard(familyMemberDTO.getIdcard());
         }

        if(Constant.DomesticRelation.ONESELF.equals(familyMemberDTO.getFamilyRelation())){
            orderEntity.setOrderId(familyMemberDTO.getOrderId());
            orderEntity.setName(familyMemberDTO.getName());
            orderEntity.setIdcard(familyMemberDTO.getIdcard());
            orderEntity.setMemberId(familyMemberDTO.getId());
        }

        if(relation!=null && Constant.DomesticRelation.ONESELF.equals(relation) && !Constant.DomesticRelation.ONESELF.equals(familyMemberDTO.getFamilyRelation())){
            orderEntity.setOrderId(familyMemberDTO.getOrderId());
            orderEntity.setName("");
            orderEntity.setIdcard("");
            orderEntity.setMemberId("");
        }
        if(StringUtils.isNotBlank(orderEntity.getOrderId())){
            int rst = orderWriteDao.updateIgnoreNull(orderEntity);
            if(rst<1){
                throw new BizException(FailureCode.ERR_9999);
            }
        }
    }

    public int updateHouseholdOrder(OrderEntity orderEntity){
        return orderWriteDao.updateHouseholdOrder(orderEntity);
    }


    public int batchUpdateSalaryNumber(List<OrderEntity> orderList) {
        return orderWriteDao.batchUpdateSalaryNumber(orderList);
    }
}
